package com.imut.lagain.repository;
import org.apache.ibatis.annotations.Select;
import org.slf4j.LoggerFactory;

import com.imut.lagain.entity.ThoughtAnalysis;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.jpa.repository.Modifying;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 思维分析数据访问层
 */
@Mapper
public interface ThoughtAnalysisRepository extends BaseMapper<ThoughtAnalysis> {

    /**
     * 根据用户ID查询思维分析记录
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.isDeleted = false ORDER BY t.createdAt DESC")
    List<ThoughtAnalysis> findByUserId(@Param("userId") Long userId);

    /**
     * 根据用户ID和会话ID查询思维分析
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.sessionId = :sessionId AND t.isDeleted = false ORDER BY t.createdAt DESC")
    List<ThoughtAnalysis> findByUserIdAndSessionId(@Param("userId") Long userId, @Param("sessionId") Long sessionId);

    /**
     * 根据用户ID和分析类型查询
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.analysisType = :analysisType AND t.isDeleted = false ORDER BY t.createdAt DESC")
    List<ThoughtAnalysis> findByUserIdAndAnalysisType(@Param("userId") Long userId, @Param("analysisType") String analysisType);

    /**
     * 根据用户ID和状态查询
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.status = :status AND t.isDeleted = false ORDER BY t.createdAt DESC")
    List<ThoughtAnalysis> findByUserIdAndStatus(@Param("userId") Long userId, @Param("status") String status);

    /**
     * 根据用户ID和时间范围查询
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.createdAt BETWEEN :startDate AND :endDate AND t.isDeleted = false ORDER BY t.createdAt DESC")
    List<ThoughtAnalysis> findByUserIdAndDateRange(@Param("userId") Long userId, 
                                                   @Param("startDate") LocalDateTime startDate, 
                                                   @Param("endDate") LocalDateTime endDate);

    /**
     * 根据分析ID查询
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.id = :analysisId AND t.isDeleted = false")
    Optional<ThoughtAnalysis> findByAnalysisId(@Param("analysisId") Long analysisId);

    /**
     * 完成思维分析
     */
    @Modifying
    @Select("UPDATE ThoughtAnalysis t SET t.status = 'completed', t.completedAt = :completedAt, t.newAnxietyLevel = :newAnxietyLevel, t.effectivenessRating = :effectivenessRating, t.updatedAt = :updatedAt WHERE t.id = :analysisId")
    int completeAnalysis(@Param("analysisId") Long analysisId, 
                        @Param("completedAt") LocalDateTime completedAt, 
                        @Param("newAnxietyLevel") Integer newAnxietyLevel, 
                        @Param("effectivenessRating") Integer effectivenessRating, 
                        @Param("updatedAt") LocalDateTime updatedAt);

    /**
     * 更新认知重构结果
     */
    @Modifying
    @Select("UPDATE ThoughtAnalysis t SET t.alternativeThoughts = :alternativeThoughts, t.balancedThought = :balancedThought, t.updatedAt = :updatedAt WHERE t.id = :analysisId")
    int updateCognitiveRestructuring(@Param("analysisId") Long analysisId, 
                                    @Param("alternativeThoughts") String alternativeThoughts, 
                                    @Param("balancedThought") String balancedThought, 
                                    @Param("updatedAt") LocalDateTime updatedAt);

    /**
     * 更新证据分析
     */
    @Modifying
    @Select("UPDATE ThoughtAnalysis t SET t.evidenceFor = :evidenceFor, t.evidenceAgainst = :evidenceAgainst, t.probabilityAssessment = :probabilityAssessment, t.updatedAt = :updatedAt WHERE t.id = :analysisId")
    int updateEvidenceAnalysis(@Param("analysisId") Long analysisId, 
                              @Param("evidenceFor") String evidenceFor, 
                              @Param("evidenceAgainst") String evidenceAgainst, 
                              @Param("probabilityAssessment") Integer probabilityAssessment, 
                              @Param("updatedAt") LocalDateTime updatedAt);

    /**
     * 统计用户分析次数
     */
    @Select("SELECT COUNT(t) FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.isDeleted = false")
    Long countByUserId(@Param("userId") Long userId);

    /**
     * 统计用户完成的分析次数
     */
    @Select("SELECT COUNT(t) FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.status = 'completed' AND t.isDeleted = false")
    Long countCompletedByUserId(@Param("userId") Long userId);

    /**
     * 统计用户各类型分析次数
     */
    @Select("SELECT t.analysisType, COUNT(t) FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.status = 'completed' AND t.isDeleted = false GROUP BY t.analysisType")
    List<Object[]> countByUserIdAndAnalysisType(@Param("userId") Long userId);

    /**
     * 查询用户平均效果评分
     */
    @Select("SELECT AVG(t.effectivenessRating) FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.effectivenessRating IS NOT NULL AND t.isDeleted = false")
    Double getAverageEffectivenessRating(@Param("userId") Long userId);

    /**
     * 查询用户平均焦虑改善程度
     */
    @Select("SELECT AVG(t.anxietyLevel - t.newAnxietyLevel) FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.anxietyLevel IS NOT NULL AND t.newAnxietyLevel IS NOT NULL AND t.isDeleted = false")
    Double getAverageAnxietyImprovement(@Param("userId") Long userId);

    /**
     * 查询用户最近的分析记录
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.isDeleted = false ORDER BY t.createdAt DESC")
    List<ThoughtAnalysis> findRecentAnalysesByUserId(@Param("userId") Long userId, org.springframework.data.domain.Pageable pageable);

    /**
     * 查询用户最常见的想法分类
     */
    @Select("SELECT t.thoughtCategory FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.thoughtCategory IS NOT NULL AND t.isDeleted = false GROUP BY t.thoughtCategory ORDER BY COUNT(t) DESC")
    List<String> getMostCommonThoughtCategories(@Param("userId") Long userId);

    /**
     * 查询用户最常见的认知偏差
     */
    @Select("SELECT t.cognitiveDistortions FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.cognitiveDistortions IS NOT NULL AND t.isDeleted = false")
    List<String> getCognitiveDistortionsByUserId(@Param("userId") Long userId);

    /**
     * 查询用户需要后续跟进的分析
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.followUpNeeded = true AND t.isDeleted = false ORDER BY t.createdAt DESC")
    List<ThoughtAnalysis> findFollowUpNeeded(@Param("userId") Long userId);

    /**
     * 查询未完成的分析
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.status IN ('pending', 'in_progress') AND t.isDeleted = false ORDER BY t.createdAt DESC")
    List<ThoughtAnalysis> findIncompleteAnalyses(@Param("userId") Long userId);

    /**
     * 查询超时未完成的分析
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.status = 'in_progress' AND t.startedAt < :timeoutThreshold AND t.isDeleted = false")
    List<ThoughtAnalysis> findTimeoutAnalyses(@Param("timeoutThreshold") LocalDateTime timeoutThreshold);

    /**
     * 查询用户高焦虑水平的想法
     */
    @Select("SELECT t FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.anxietyLevel >= :threshold AND t.isDeleted = false ORDER BY t.anxietyLevel DESC")
    List<ThoughtAnalysis> findHighAnxietyThoughts(@Param("userId") Long userId, @Param("threshold") Integer threshold);

    /**
     * 查询用户最有效的分析类型
     */
    @Select("SELECT t.analysisType FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.effectivenessRating >= 4 AND t.isDeleted = false GROUP BY t.analysisType ORDER BY COUNT(t) DESC")
    List<String> getMostEffectiveAnalysisTypes(@Param("userId") Long userId);

    /**
     * 查询用户的洞察记录
     */
    @Select("SELECT t.insights FROM ThoughtAnalysis t WHERE t.userId = :userId AND t.insights IS NOT NULL AND t.isDeleted = false ORDER BY t.createdAt DESC")
    List<String> getInsightsByUserId(@Param("userId") Long userId);
}
